<?php

namespace app\api\controller;

use app\api\model\User as UserModel;
use think\Request;

/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends Controller
{
    /**
     * 用户自动登录
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $model = new UserModel;
        return $this->renderSuccess([
            'user_id' => $model->login($this->request->post()),
            'token' => $model->getToken()
        ]);
    }

    /**
     * 当前用户详情
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        return $this->renderSuccess(compact('userInfo'));
    }

    /**
     * 申请会员业务逻辑接口
     * @param Request|null $request
     * @return array|void
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function member(Request $request=null){
        $param = $request->param();
        if(empty($param['real_name'])){
            return $this->renderError('用户真实姓名不允许为空');
        }
        if(empty($param['mobile'])){
            return $this->renderError('用户手机号不允许为空');
        }
        $userInfo = $this->getUser();
        $userInfo->real_name = $param['real_name'];
        $userInfo->mobile = $param['mobile'];
        $userInfo->grade_id = 1;
        $result = $userInfo->save();
        if($result){
            return $this->renderSuccess($result,'申请会员成功');
        }else{
            return $this->renderError('申请会员失败!');
        }
    }

    /**
     * 获取用户手机号
     * @param Request|null $request
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function getPhone(Request $request=null){
        $model = new UserModel;
        $code = $request->param('code');
        if(empty($code)){
            return $this->renderError('code不允许为空!');
        }
        $result = $model->getUserPhone($code);
        $data = json_decode($result,true);
        $phone = '';
        if(!empty($data['phone_info']['phoneNumber'])){
            $phone = $data['phone_info']['phoneNumber'];
        }
        return $this->renderSuccess(['phone'=>$phone]);
    }

    /**
     * 获取用户手机号
     * @return array
     * @throws \think\exception\DbException
     */
    public function getCustomer(){
        $detail = \app\common\model\Setting::detail('customer');
        return $this->renderSuccess($detail['values']);
    }

}
